<template>
  <div class="table-content">
    <div class="toolbar">
      <button @click="importClipboard"><svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-daoru"></use>
          </svg> 剪切板导入</button>
      <button @click="selectFile"><svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-daoru"></use>
          </svg> 文件导入</button>
      <input
        type="file"
        name="file"
        @change="importData"
        :accept="fileAccept"
        ref="file"
        style="display: none"
      />
      <button @click="exportClipboard">
        <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-daochu"></use>
          </svg> 剪切板导出
      </button>
      <button @click="exportData">
        <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-daochu"></use>
          </svg> 文件导出
      </button>
      <button @click="loadDiagram" :disabled="currentId == null">
        <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-chakan"></use>
          </svg> 查看
      </button>
      <button @click="remove">
        
        <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-icon-lajitong-sel"></use>
          </svg> 删除
      </button>
      <div class="keyword">
        <svg class="icon search" aria-hidden="true">
            <use xlink:href="#icon-sousuo"></use>
          </svg>
        <select v-model="searchType" @change="searchTypeChange">
          <option value="keyword">模糊</option>
          <option value="^keyword$">精确</option>
          <option value="^keyword">开头</option>
          <option value="keyword$">结尾</option>
        </select>
        <input type="text" v-model="keyword" placeholder="搜索关键字" />
      </div>
    </div>

    <div class="table-content">
      <div class="table-header">
        <div class="th">
          <input
            type="checkbox"
            class="selector"
            :checked="isAllSelected"
            @change="selectAllRows()"
          />
        </div>
        <div class="th">卦主</div>
        <div class="th">问题</div>
        <div class="th">本卦</div>
        <div class="th">变卦</div>
        <div class="th">问卦时间</div>
        <div class="th">四柱</div>
      </div>
      <div v-if="allData" class="table-body">
        <RecycleScroller
          :items="allData"
          :item-size="30"
          key-field="id"
          class="scroller"
        >
          <template slot-scope="{ item }">
            <div
              class="row"
              @click="currentId = item.id"
              :class="{ selected: item.id == currentId }"
              @dblclick="
                currentId = item.id;
                loadDiagram();
              "
            >
              <div class="td">
                <input
                  type="checkbox"
                  class="selector"
                  :checked="isRowSelected(item.id)"
                  @change="selectRow(item.id)"
                />
              </div>
              <div class="td">{{ item.owner }}</div>
              <div class="td">{{ item.question }}</div>
              <div class="td">{{ item.mainDiagram }}</div>
              <div class="td">{{ item.changeDiagram }}</div>
              <div class="td">{{ item.createDatetime }}</div>
              <div class="td">
                {{ item.year }} {{ item.month }} {{ item.date }} {{ item.time }}
              </div>
            </div>
          </template>
        </RecycleScroller>
      </div>
    </div>
    <div
      class="modal"
      :class="{ show: showCopyModal }"
      style="background: #fff"
    >
      <div class="close" @click="showCopyModal = false"></div>
      <div class="modal-content">
        <div style="flex: 1">
          您可以全选以下文字内容，复制后分享给其他道友：
          <textarea
            :value="copyContent"
            style="width: 100%; height: 100%"
            readonly
          ></textarea>
        </div>
      </div>
    </div>
    <div
      class="modal"
      :class="{ show: showPasteModal }"
      style="background: #fff"
    >
      <div class="close" @click="showPasteModal = false"></div>
      <div class="modal-content" style="padding: 8vmin">
        <div style="flex: 1">
          <textarea
            v-model="pasteContent"
            style="width: 100%; height: 100%"
            placeholder="请将已复制的卦例信息粘贴到这里"
          ></textarea>
          <button style="margin: 0" @click="importFromText()"><svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-daoru"></use>
          </svg> 导入</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { EventBus } from "../core/event-bus";
import showMessage from "./messageBox";
import { RecycleScroller } from "vue-virtual-scroller";
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
import runInApp from "../core/run-in-app";

export default {
  name: "customerList",
  data() {
    return {
      currentId: null,
      allData: [],
      keyword: "",
      selectedIds: [],
      searchType: "keyword",
      showCopyModal: false,
      copyContent: "",
      showPasteModal: false,
      pasteContent: "",
    };
  },
  props: ["tableName"],
  methods: {
    remove() {
      if (this.selectedIds.length == 0) {
        showMessage("请勾选要删除的记录");
        return;
      }

      showMessage(
        "确定删除勾选的" + this.selectedIds.length + "条记录吗？删除后不可恢复",
        "confirm"
      ).then((res) => {
        if (res == "ok") {
          this.selectedIds.forEach((id) => {
            this.$global.db.delete(this.tableName, id, () => {
              this.allData.splice(
                this.allData.findIndex((x) => x.id == id),
                1
              );
            });
          });
          this.currentId = null;
        }
      });
    },
    loadDiagram() {
      this.$global.db.get(this.tableName, this.currentId, (data) => {
        if (data) {
          EventBus.$emit(`${this.tableName}-load-diagram`, data);
          EventBus.$emit(`load-diagram`, data);
        }
      });
    },
    exportData() {
      if (this.selectedIds.length == 0) {
        showMessage("请勾选要导出的记录");
        return;
      }
      const dataToExport = this.getSelectedData();

      const jsonData = JSON.stringify({
        tableName: this.tableName,
        data: dataToExport,
      });

      if(runInApp.is()){
        runInApp.exportFile(`hexagram-${Date.now()}${this.ext}`, jsonData);
      }

      const blob = new Blob([jsonData]);
      const url = URL.createObjectURL(blob);

      const a = document.createElement("a");
      a.href = url;
      a.download = `hexagram-${Date.now()}${this.ext}`;
      document.body.appendChild(a);
      a.click();

      URL.revokeObjectURL(url);
      document.body.removeChild(a);
    },
    exportClipboard() {
      if (this.selectedIds.length == 0) {
        showMessage("请勾选要导出的记录");
        return;
      }

      const dataToExport = this.getSelectedData();

      let jsonData = JSON.stringify({
        tableName: this.tableName,
        data: dataToExport,
      });

      showMessage("剪切板导出只适合导出少量卦例的场景，如果量很大推荐使用文件导出\n新卦例适合分享时用，原卦例适合自己备份少量卦例时用", "customize", [{command: "y", text: "新卦例"}, {command: "n", text:"原卦例"}]).then(async res => {
        if(res == "y"){
          const newJsonData = JSON.parse(jsonData);
          if(newJsonData.data){
            for (let i = 0; i < newJsonData.data.length; i++) {
              newJsonData.data[i].id = await new Promise(resolve => {
                  setTimeout(() => {
                    resolve(this.$global.db.generateId());
                  }, 1);
              });
            }
            jsonData = JSON.stringify(newJsonData);
          }
          
        }
        this.showCopyModal = true;
        this.copyContent = jsonData;
      });
      

      // if (this.canAccessClipboard) {
      //   navigator.clipboard.writeText(jsonData).then(() => {
      //     showMessage("已将所选案例复制到剪切板");
      //   });
      // } else {
      
      // }
    },
    selectFile() {
      this.$refs.file.click();
    },
    importData(event) {
      if (event.target.files.length == 1) {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.readAsText(file, "utf-8");

        reader.onloadend = (e) => {
          const text = e.target.result;
          try {
            const data = JSON.parse(text);
            if (data.tableName == this.tableName && data && data.data) {
              this.$global.db.importData(this.tableName, data.data);
              showMessage("从文件导入完毕");
            } else throw new Error();
          } catch {
            showMessage("导入失败");
          }
        };
      }
    },
    importClipboard() {
      // if (this.canAccessClipboard) {
      //   navigator.clipboard.readText().then((x) => {
      //     try {
      //       const data = JSON.parse(x);
      //       if (data.tableName == this.tableName && data && data.data) {
      //         this.$global.db.importData(this.tableName, data.data);
      //         showMessage("从剪切板导入完毕");
      //       } else throw new Error();
      //     } catch {
      //       showMessage("导入失败");
      //     }
      //   });
      // } else {
      this.showPasteModal = true;
      // }
    },
    importFromText() {
      try {
        const data = JSON.parse(this.pasteContent);
        if (data.tableName == this.tableName && data && data.data) {
          this.$global.db.importData(this.tableName, data.data);
          showMessage("从剪切板导入完毕").then(() => {
            this.showPasteModal = false;
          });
        } else throw new Error();
      } catch {
        showMessage("导入失败");
      }
    },
    isRowSelected(id) {
      return this.selectedIds.includes(id);
    },
    selectRow(id) {
      if (this.isRowSelected(id))
        this.selectedIds.splice(this.selectedIds.indexOf(id), 1);
      else this.selectedIds.push(id);
    },
    selectAllRows() {
      if (this.isAllSelected) this.selectedIds = [];
      else this.selectedIds = this.allData.map((x) => x.id);
    },
    getSelectedData() {
      return this.allData.filter((x) => this.selectedIds.includes(x.id));
    },
    search() {
      try{
        const regex = new RegExp(
          this.searchType.replace("keyword", this.keyword || ".*")
        );
        this.allData = this.$global.db[this.tableName].filter((x) =>
          Object.values(x).some((y) => y && typeof y == "string" && regex.test(y))
        );
        this.selectedIds = [];
        }
      catch {
        return;
      }
    },
    searchTypeChange() {
      this.search();
    },
  },
  watch: {
    tableName(newVal) {
      this.allData = this.$global.db[newVal];
    },
    keyword(newVal) {
      this.search();
    },
    showCopyModal(newVal) {
      if (!newVal) {
        this.copyContent = "";
      }
    },
    showPasteModal(newVal) {
      if (!newVal) {
        this.pasteContent = "";
      }
    },
  },
  computed: {
    ext() {
      if (this.tableName == "hexagrams") return ".ham";
      //if(this.tableName == "plumagrams")
      else return ".pam";
    },
    fileAccept() {
      if (this.tableName == "hexagrams") return ".ham,.hgm";
      //if(this.tableName == "plumagrams")
      else return ".pam,.pgm";
    },
    isAllSelected() {
      return this.allData.length == this.selectedIds.length;
    },
    // canAccessClipboard() {
    //   return navigator.clipboard;
    // },
  },
  mounted: function () {
    //当所有卦例都从数据库中加载完毕时，更新数据源，每次增删改，都会触发以下事件
    EventBus.$on("customer-data-loaded", () => {
      // this.allData = this.$global.db[this.tableName];
      this.search();
    });
  },
  components: {
    RecycleScroller,
  },
};
</script>

<style lang="scss">
.table-content {
  flex: 1;
  height: 100vh;

  .table-header {
    display: flex;
  }
  .table-body {
    height: 72vh;
  }
  .scroller {
    height: 78vh;
    background: #fff;
  }

  .vue-recycle-scroller__slot,
  .vue-recycle-scroller__item-view {
    display: flex;
    width: 100%;
  }
  .th,
  .td {
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding: 0 5px;
    border: solid 1px #eee;
    line-height: 30px;
  }
  .th {
    background: #000;
    color: #fff;
    border: 0;
    font-size: 13px;
  }
  .row {
    display: flex;
    width: 100%;
    height: 30px;
    .td{
      font-size: 13px;
    }
    // border-bottom: solid 1px #eee;
    &.selected {
      background: #40c4ff;
      .td{
      color: #fff;
      }
    }
  }
  .selector {
    width: 3vmin;
    height: 3vmin;
  }
  .th:nth-child(1) {
    width: 40px;
    flex: none;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .th:nth-child(3) {
    flex: 2;
  }
  .vue-recycle-scroller__item-view .td:nth-child(1) {
    width: 40px;
    flex: none;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .vue-recycle-scroller__item-view .td:nth-child(3) {
    flex: 2;
  }
  .toolbar {
    text-align: left;
    margin-bottom: 2vh;
    display: flex;
    :nth-child(1) {
      margin: 0;
    }
    .keyword {
      margin-left: auto;
      margin-right: 0;
      position: relative;
      border-bottom: solid 1px #ccc;
      // padding-left: 5vmin;
      select {
        outline: none;
        border: 0;
        background: none;
      }
      input {
        outline: none;
        border: 0;
        background: transparent;
        text-indent: 4vmin;
        width: 30vmin;
      }

      // &::before {
      //   content: "🔍";
      //   position: absolute;
      //   left: 0;
      // }
    }
  }
}
</style>
